const path = require('path');
const fs = require('fs');
const rimraf = require('rimraf');
const nodeTools = require('@seeyon/node-tools');
const { resolveApp } = require('./resolve');
const { clientParams } = require('./utils');

// 获取dist下的所有文件，将体积超标的js文件筛选出来，存入一个文件然后上传至OSS服务器
const filterFatFiles = async function () {
  if (
    !fs.existsSync(`${resolveApp('package.json')}`) ||
    !fs.existsSync(`${path.resolve('dist')}`)
  ) {
    return;
  }
  const { name } = require(`${resolveApp('package.json')}`);
  // 尺寸标准，单位kb
  const maxSize = 100 * 1024;
  // 用于存储体积超标的文件名称
  const fileName = `${name}.json`;
  // 体积超标的文件列表
  let fatFiles = [];
  // 获取dist下的所有文件
  fs.readdir(path.resolve('dist'), function (error, files) {
    error && console.log(error);
    files.length > 0 && getAndFilterFiles(files.filter((file) => file.endsWith('.js')));
  });
  // 筛选出体积超标的js文件
  const getAndFilterFiles = (files) => {
    const allFiles = Object.values(files);
    const filePromise = [];
    allFiles.forEach((file) => {
      filePromise.push(
        new Promise((resolve, reject) => {
          fs.stat(path.resolve(`dist/${file}`), function (error, stats) {
            error && reject(error);
            const obj = Object.create(null);
            obj[file] = stats.size;
            resolve(obj);
          });
        }),
      );
    });
    // 待所有文件的体积读取完成后，执行存文件的操作
    Promise.all(filePromise).then((values) => {
      const fileList = values.filter((file) => Object.values(file) > maxSize);
      fatFiles = fileList.map((file) => Object.keys(file)[0]);
      // 存储为一个文件
      fatFilesStr = JSON.stringify(fatFiles);
      createFolder(path.resolve(__dirname, 'fatFiles'));
      createFile(fatFilesStr);
      uploadFilesToAli();
    });
    // 创建目录
    const createFolder = (path) => {
      !fs.existsSync(path) && fs.mkdirSync(path);
    };
    // 创建文件
    const createFile = (str) => {
      fs.writeFileSync(path.resolve(__dirname, `./fatFiles/${fileName}`), `{"files": ${str}}`);
    };

    // 上传阿里云OSS
    const uploadFilesToAli = async () => {
      try {
        // OSS目标路径
        const targetFloder = 'static/fatfiles';
        // dev环境的桶
        const devBucket = 'seeyon-frontend';
        // test环境的桶
        const testBucket = 'seeyon-test-public';

        const params = {
          uploadTargetType: 'ali',
          clientParams: { ...clientParams, ...{ bucket: devBucket } },
          sourceFloder: path.resolve(__dirname, 'fatFiles'),
          targetFloder,
        };
        await nodeTools.uploadFiles(params);
        const msg = `成功将文件【${fileName}】上传至阿里云【${devBucket}】桶的【${targetFloder}】目录`;
        console.info(msg);

        const params2 = {
          ...params,
          ...{
            clientParams: { ...clientParams, ...{ bucket: testBucket } },
          },
          targetFloder,
        };
        await nodeTools.uploadFiles(params2);
        const msg2 = `成功将文件【${fileName}】上传至阿里云【${testBucket}】桶的【${targetFloder}】目录`;

        console.info(msg2);
        rimraf.sync(path.resolve(__dirname, 'fatFiles'));
        return Promise.resolve(msg);
      } catch (error) {
        console.error(error);
      }
    };
  };
};

filterFatFiles();

module.exports = {
  filterFatFiles,
};
